package com.anolesoft.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;

@RestController
public class fileController {
    @RequestMapping("/file")
    @ResponseBody
    public void file(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("file");
        String path =  File.separator + name;

        File imageFile = new File(path);
        System.out.println(imageFile.getAbsolutePath());
        if (!imageFile.exists()) {
            return;
        }

        //下载的文件携带这个名称
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        //文件下载类型--二进制文件
        response.setContentType("application/octet-stream");

        try {
            FileInputStream fis = new FileInputStream(path);
            byte[] content = new byte[fis.available()];
            fis.read(content);
            fis.close();

            ServletOutputStream sos = response.getOutputStream();
            sos.write(content);

            sos.flush();
            sos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    }
